package com.njlime.cms.controller.sys;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.njlime.cms.entities.Label;
import com.njlime.cms.entities.Live;
import com.njlime.cms.entities.LiveComment;
import com.njlime.cms.entities.LiveConfig;
import com.njlime.cms.sdk.letv.LetvApiClient;
import com.njlime.cms.sdk.letv.LetvApiUtil;
import com.njlime.cms.sdk.letv.LetvUtil;
import com.njlime.cms.service.sys.*;
import com.njlime.core.base.controller.BaseController;
import com.njlime.core.exception.ExceptionState;
import com.njlime.core.helper.GlobalValue;
import com.njlime.core.helper.PageBean;
import com.njlime.core.web.validation.annotation.support.ValidateService;
import com.njlime.member.entiies.MemberComment;
import com.njlime.sys.entities.Unit;
import com.njlime.sys.entities.UnitWxConfig;
import com.njlime.sys.security.util.UserUtils;
import org.apache.http.HttpResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 直播控制器
 * Created by Dean on 2017/8/11.
 */
@Controller
@RequestMapping(value = "/cms/live")
public class LiveController extends BaseController {

    private static String VER = "3.0";
    @Resource
    private LiveService liveService;
    @Resource
    private LiveCommentService liveCommentService;
    @Resource
    private LabelService labelService;
    @Resource
    private ChannelService channelService;
    @Resource
    private ColumnService columnService;
    @Resource
    private LiveConfigService liveConfigService;


    //--------------------控制器-------------------------

    /**
     * 跳转贴吧管理页面
     * @return
     */
    @RequestMapping(value = "liveManage")
    public ModelAndView infoManage(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("/sys/content/live/index");
        PageBean pageBean = new PageBean();
        pageBean.setPageSize(Integer.MAX_VALUE);
        modelAndView.addObject("labelList",labelService.list(pageBean, new Label()).getMapList());
        //频道栏目
        Unit rootUnit = getLoginUser().getRootUnit();
        if(rootUnit != null){
            modelAndView.addObject("channelList",channelService.getChannelList(rootUnit.getId(),3));
        }
        return modelAndView;
    }

    /**
     * 跳转贴吧编辑页面
     * @return
     */
    @RequestMapping(value = "editView")
    public ModelAndView editView(HttpServletRequest request, Integer id) {
        ModelAndView modelAndView = new ModelAndView("/sys/content/live/edit");
        //标签
        PageBean pageBean = new PageBean();
        pageBean.setPageSize(Integer.MAX_VALUE);
        modelAndView.addObject("labelList",labelService.list(pageBean, new Label()).getMapList());
        //资讯详情
        Live live = liveService.findOne(id);
        checkDataPermission(live.getUnit_id(), live.getCreator());
        modelAndView.addObject("info", live);
        //频道栏目
        Unit rootUnit = getLoginUser().getRootUnit();
        modelAndView.addObject("channelList",channelService.getChannelList(rootUnit.getId(),3));
        return modelAndView;
    }

    /**
     * 跳转贴吧新增页面
     * @return
     */
    @RequestMapping(value = "addView")
    public ModelAndView addView(HttpServletRequest request) {
        //标签
        ModelAndView modelAndView = new ModelAndView("/sys/content/live/add");
        PageBean pageBean = new PageBean();
        pageBean.setPageSize(Integer.MAX_VALUE);
        modelAndView.addObject("labelList",labelService.list(pageBean, new Label()).getMapList());
        //频道栏目
        Unit rootUnit = getLoginUser().getRootUnit();
        modelAndView.addObject("channelList",channelService.getChannelList(rootUnit.getId(),3));
        return modelAndView;
    }

    /**
     * 跳转贴吧评论页面
     * @return
     */
    @RequestMapping(value = "commentView")
    public ModelAndView commentView(HttpServletRequest request, Integer id) {
        ModelAndView modelAndView = new ModelAndView("/sys/content/live/comment");
        Live live = liveService.findOne(id);
        checkDataPermission(live.getUnit_id(), live.getCreator());
        modelAndView.addObject("info", live);
        return modelAndView;
    }

    //------------------功能--------------------------

    @RequestMapping(value = "info", method = RequestMethod.GET)
    @ResponseBody
    public String info(int id) {
        Live live = liveService.findOne(id);
        checkDataPermission(live.getUnit_id(), live.getCreator());
        return toJsonSuccessData(liveService.findOne(id));
    }


    /**
     * 编辑直播
     * @param live
     * @return
     */
    @RequestMapping(value = "edit", method = RequestMethod.POST)
    @ResponseBody
    public String edit(Live live) {
        try {
            Unit unit = getLoginUser().getRootUnit();
            if(unit == null){
                return toJsonErrorData(ExceptionState.MANAGER_EXCEPTION);
            }
            Live ori = liveService.findOne(live.getId());
            checkDataPermission(ori.getUnit_id(), ori.getCreator());
            if(live.getLive_end_time() != null && live.getLive_end_time().getTime() > new Date().getTime()){
                Map<String, String> params = new HashMap<String, String>();
                Live item = liveService.findOne(live.getId());
                params.put("activityId", item.getActivity_id());
                params.put("activityName", item.getTitle());

                if (live.getLive_start_time() != null) {
                    //1970年开始的毫秒数
                    params.put("startTime", item.getLive_start_time().getTime() + "");
                }
                if (live.getLive_end_time() != null) {
                    //1970年开始的毫秒数
                    params.put("endTime", item.getLive_end_time().getTime() + "");
                }
                params.put("coverImgUrl", item.getSurface_plot() + "");
                params.put("description", item.getAbstract_info());
                LiveConfig liveConfig = liveConfigService.getConfig(unit.getId());
                if(liveConfig == null){
                    return toJsonErrorData(ExceptionState.UNKNOWN_EXCEPTION, "请先进行直播设置");
                }
                HttpResponse response = LetvUtil.initClient(liveConfig.getUserid(),liveConfig.getSecret()).executePost(
                        "lecloud.cloudlive.activity.modify", "4.0", params);
                System.out.println("" + response.getStatusLine().getStatusCode());
                int statusCode = response.getStatusLine().getStatusCode();
                String reusltS = LetvApiUtil.getResponseBody(response);
                if (statusCode != 200) {
                    JSONObject resultObj = JSON.parseObject(reusltS);
                    return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "" + resultObj.getString("errMsg"));
                }
            }
            int count = liveService.editLive(live);
            if (count > 0) {
                return toJsonSuccessData();
            } else {
                return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "修改失败");
            }
        } catch (Exception e) {
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "修改失败");
        }
    }

    /**
     * 回看地址
     * @param live
     * @return
     */
    @RequestMapping(value = "liveReview", method = RequestMethod.POST)
    @ResponseBody
    public String liveReview(Live live) {
        try {
            int count = liveService.editLive(live);
            if (count > 0) {
                return toJsonSuccessData();
            } else {
                return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "修改失败");
            }
        } catch (Exception e) {
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "修改失败");
        }

    }

    /**
     * 创建直播
     * @param live
     * @param request
     * @return
     */
    @RequestMapping(value = "add", method = RequestMethod.POST)
    @ResponseBody
    public String add(Live live, HttpServletRequest request) {
        try {
            Unit unit = getLoginUser().getRootUnit();
            if(unit == null){
                return toJsonErrorData(ExceptionState.MANAGER_EXCEPTION);
            }
            ValidateService.valid(live);
            //请勿修改以下顺序
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            Map<String, String> params = new HashMap<String, String>();
            params.put("activityName", live.getTitle());
            params.put("activityCategory", "001");
            params.put("startTime", sdf.format(live.getLive_start_time()));
            params.put("endTime", sdf.format(live.getLive_end_time()));
            params.put("coverImgUrl", live.getSurface_plot() + "");
            params.put("description", live.getAbstract_info());
            params.put("playMode", "0");
            params.put("liveNum", "1");
            params.put("codeRateTypes", "16,13,10");
            params.put("needRecord", "1");
            params.put("needTimeShift", "0");

            LiveConfig liveConfig = liveConfigService.getConfig(unit.getId());
            if(liveConfig == null){
                return toJsonErrorData(ExceptionState.UNKNOWN_EXCEPTION, "请先进行直播设置");
            }
            HttpResponse response = LetvUtil.initClient(liveConfig.getUserid(),liveConfig.getSecret()).executePost(
                    "letv.cloudlive.activity.create", VER, params);
            String reusltS = LetvApiUtil.getResponseBody(response);
            JSONObject resultObj = JSONObject.parseObject(reusltS);
            live.setActivity_id(resultObj.getString("activityId"));
            try {
                if (!resultObj.getString("errCode").equals("200")) {
                    return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, resultObj.getString("errMsg"));
                }
            } catch (Exception e) {

            }

            /*
            Map<String, String> getPlayPageUrlParams = new HashMap<String, String>();
            getPlayPageUrlParams.put("activityId", live.getActivity_id());
            HttpResponse response1 = letvApiClient.executeGet("letv.cloudlive.activity.playerpage.getUrl", VER, getPlayPageUrlParams);
            String reusltP = LetvApiUtil.getResponseBody(response1);
            JSONObject resultObjPage = JSONObject.parseObject(reusltS);*/

            live.setUnit_id(getLoginUserUnitId());
            live.setComment_num(0);
            live.setIs_comment(GlobalValue.NO);
            live.setReading(0);
            live.setCreator(getLoginUser().getId());
            int count = liveService.save(live);
            if (count > 0) {
                return toJsonSuccessData();
            } else {
                return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "新增失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, e.getMessage());
        }
    }

    /**
     * 删除直播
     * @param request
     * @param id
     * @return
     */
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    @ResponseBody
    public String del(HttpServletRequest request, Integer id) {
        Live live = liveService.findOne(id);
        checkDataPermission(live.getUnit_id(), live.getCreator());
        int count = liveService.del(id);
        if (count > 0) {
            return toJsonSuccessData();
        } else {
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "删除失败");
        }
    }

    /**
     * 评论开关
     *
     * @param request
     * @param id
     * @return
     */
    @RequestMapping(value = "toggleComment", method = RequestMethod.POST)
    @ResponseBody
    public String toggleComment(HttpServletRequest request, Integer id) {
        Live live = liveService.findOne(id);
        checkDataPermission(live.getUnit_id(), live.getCreator());
        int count = liveService.toggleComment(id);
        if (count > 0) {
            return toJsonSuccessData();
        } else {
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "操作失败");
        }
    }

    /**
     * 上下线
     *
     * @param request
     * @param info
     * @return
     */
    @RequestMapping(value = "togglePublish", method = RequestMethod.POST)
    @ResponseBody
    public String togglePublish(HttpServletRequest request, Live info) {
        Live live = liveService.findOne(info.getId());
        checkDataPermission(live.getUnit_id(), live.getCreator());
        int count = liveService.togglePublish(info);
        if (count > 0) {
            return toJsonSuccessData();
        } else {
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "操作失败");
        }
    }

    /**
     * 获取直播推送token
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getPushToken", method = RequestMethod.GET)
    public String getPushToken(int id) {
        Unit unit = getLoginUser().getRootUnit();
        if(unit == null){
            return toJsonErrorData(ExceptionState.MANAGER_EXCEPTION);
        }
        Live live = liveService.findOne(id);
        checkDataPermission(live.getUnit_id(), live.getCreator());
        if (live.getActivity_id() == null || live.getActivity_id().equals("")) {
            return toJsonErrorData(ExceptionState.UNKNOWN_EXCEPTION, "该直播存在错误");
        }
        Map<String, String> getPlayPageUrlParams = new HashMap<String, String>();
        getPlayPageUrlParams.put("activityId", live.getActivity_id());
        try {
            LiveConfig liveConfig = liveConfigService.getConfig(unit.getId());
            if(liveConfig == null){
                return toJsonErrorData(ExceptionState.UNKNOWN_EXCEPTION, "请先进行直播设置");
            }
            HttpResponse response1 = LetvUtil.initClient(liveConfig.getUserid(),liveConfig.getSecret()).executeGet(
                    "lecloud.cloudlive.activity.getPushUrl", "4.0", getPlayPageUrlParams);
            if (response1.getStatusLine().getStatusCode() == 200) {
                String reusltP = LetvApiUtil.getResponseBody(response1);
                JSONObject resultObjPage = JSONObject.parseObject(reusltP);
                return toJsonSuccessData(resultObjPage);
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
        return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "获取直播串流码失败");
    }

    /**
     * 获取热点列表
     *
     * @param pageBean
     * @param live
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public String list(PageBean pageBean, Live live, HttpServletRequest request) {
        return toJsonListData(liveService.list(pageBean, live));
    }


    /**
     * 文章评论列表获取
     *
     * @param pageBean
     * @param comment
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "commentList", method = RequestMethod.GET)
    public String list(PageBean pageBean, LiveComment comment, HttpServletRequest request) {
        Live live = liveService.findOne(comment.getLive_id());
        checkDataPermission(live.getUnit_id(), live.getCreator());
        return toJsonListData(liveCommentService.list(pageBean, comment));
    }

    /**
     * 审核
     *
     * @param id 文章id
     * @return
     */
    @RequestMapping(value = "commentAudit", method = RequestMethod.POST)
    @ResponseBody
    public String commentAudit(int id) {
        LiveComment comment = liveCommentService.findOne(id);
        Live live = liveService.findOne(comment.getLive_id());
        checkDataPermission(live.getUnit_id(), live.getCreator());
        MemberComment memberComment = new MemberComment();
        memberComment.setMember_id(comment.getUser_id());
        memberComment.setBusiness_id(comment.getLive_id());
        memberComment.setBusiness_type(GlobalValue.BusinessType.INFORMATION);
        memberComment.setBusiness_title(live.getTitle());
        memberComment.setCreate_time(new Date());
        liveCommentService.auditComment(comment, memberComment);
        return toJsonSuccessData();
    }


    /**
     * 删除 文章评论
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "commentDel", method = RequestMethod.POST)
    @ResponseBody
    public String liveCommentDel(HttpServletRequest request, LiveComment comment) {
        Live live = liveService.findOne(comment.getLive_id());
        checkDataPermission(live.getUnit_id(), live.getCreator());
        int count = liveCommentService.del(comment);
        if (count > 0) {
            return toJsonSuccessData();
        } else {
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "删除失败");
        }
    }

    /**
     * 直播评论置顶
     *
     * @param id 文章id
     * @return
     */
    @RequestMapping(value = "commentTop", method = RequestMethod.POST)
    @ResponseBody
    public String commentTop(int id) {
        LiveComment comment = liveCommentService.findOne(id);
        Live live = liveService.findOne(comment.getLive_id());
        checkDataPermission(live.getUnit_id(), live.getCreator());
        liveCommentService.top(id);
        return toJsonSuccessData();
    }

    /**
     * 文章评论点赞数  +1
     *
     * @param id 文章id
     * @return
     */
    @RequestMapping(value = "commentFabulous", method = RequestMethod.POST)
    @ResponseBody
    public String updateFabulousNum(int id) {
        LiveComment comment = liveCommentService.findOne(id);
        Live live = liveService.findOne(comment.getLive_id());
        checkDataPermission(live.getUnit_id(), live.getCreator());
        liveCommentService.like(id);
        return toJsonSuccessData();
    }

    /**
     * 回复
     *
     * @param comment
     * @return
     */
    @RequestMapping(value = "commentReply", method = RequestMethod.POST)
    @ResponseBody
    public String liveCommentReply(HttpServletRequest request, LiveComment comment) {
        LiveComment ori = liveCommentService.findOne(comment.getId());
        Live live = liveService.findOne(ori.getLive_id());
        checkDataPermission(live.getUnit_id(), live.getCreator());
        liveCommentService.reply(comment.getId(), comment.getReply(), getLoginUser().getId());
        return toJsonSuccessData();
    }

    /**
     * 获取设置
     * @param request
     * @param liveConfig
     * @return
     */
    @RequestMapping(value = "getConfig", method = RequestMethod.GET)
    @ResponseBody
    public String getConfig(HttpServletRequest request, LiveConfig liveConfig) {
        Unit unit = getLoginUser().getRootUnit();
        if (unit != null) {
            if (!unit.getId().equals(getLoginUserUnitId())) {
                return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "越权操作");
            }
            return toJsonSuccessData(liveConfigService.getConfig(unit.getId()));
        }else{
            return toJsonErrorData(ExceptionState.MANAGER_EXCEPTION);
        }
    }

    /**
     * 直播设置
     * @param request
     * @param liveConfig
     * @return
     */
    @RequestMapping(value = "setConfig", method = RequestMethod.POST)
    @ResponseBody
    public String setConfig(HttpServletRequest request, LiveConfig liveConfig) {
        Unit unit = getLoginUser().getRootUnit();
        if (unit != null) {
            if (!unit.getId().equals(getLoginUserUnitId())) {
                return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "越权操作");
            }
            liveConfig.setUnit_id(unit.getId());
            try{
                ValidateService.valid(liveConfig);
            }catch (Exception e){
                return toJsonErrorData(ExceptionState.PARAM_EXCEPTION, e.getMessage());
            }
            liveConfigService.setConfig(liveConfig);
            return toJsonSuccessData();
        }else{
            return toJsonErrorData(ExceptionState.MANAGER_EXCEPTION);
        }

    }

    /**
     * 编辑单位
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "edit" )
    public String edit(HttpServletRequest request, LiveConfig info, Integer userConfigId ){
        try {
            int unitId = UserUtils.getUser().getRootUnit().getId();

            info.setUnit_id(unitId);
            liveConfigService.edit(info,userConfigId);
            return toJsonSuccessData();
        } catch (Exception e) {
            return toJsonErrorData(ExceptionState.PARAM_EXCEPTION, e.getMessage());
        }
    }
}
